package cn.zdm.demo2.auth.util;


import cn.zdm.demo2.auth.constant.BrowserType;
import cn.zdm.demo2.auth.constant.FileFormatEnum;
import lombok.extern.slf4j.Slf4j;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.InputStreamReader;

/**
 * copyright (C), 2021, 武大吉奥科技有限公司
 *
 * @Program demo2
 * @Description 文件流操作工具类
 * @Author ZhaoDeman
 * @Create 2021/1/27 17:50
 * @Version 1.0.0
 * <author>                <time>                  <version>                   <description>
 * ZhaoDeman        2021/1/27 17:50                 1.0                        文件流操作工具累
 */
@Slf4j
public class FileUtil {
    private FileUtil() {

    }

    private static FileUtil instance;

    public static synchronized FileUtil getInstance() {
        if (instance == null) {
            instance = new FileUtil();
        }
        return instance;
    }

    /**
     * 校验文件名是否是dox
     *
     * @param file 文件
     * @return
     */
    public boolean validateFileName(MultipartFile file) {
        String fileName = file.getOriginalFilename();
        if (fileName == null || StringUtils.isEmpty(fileName)) {
            return false;
        }
        String fileSuffix = fileName.substring(fileName.lastIndexOf(".") + 1);
        if (fileSuffix.equals(FileFormatEnum.DOCX)) {
            return true;
        }
        return false;
    }

    /**
     * 读取文件数据，将字节流转换成String,通过转换后的String 在进行操作
     *
     * @param file 文件流
     * @return
     */
    public String readFile(MultipartFile file) {
        BufferedReader bufferedReader;
        StringBuffer res = new StringBuffer();
        try {
            InputStream inputStream = file.getInputStream();
            InputStreamReader inputStreamReader = new InputStreamReader(inputStream, "UTF-8");
            bufferedReader = new BufferedReader(inputStreamReader);
            String tempString;
            while ((tempString = bufferedReader.readLine()) != null) {
                res.append(tempString);
            }
            bufferedReader.close();
            inputStreamReader.close();
        } catch (Exception e) {
            log.info("文件读取失败====>{}", e);
        }
        return res.toString();
    }

    /**
     * 文件下载
     *
     * @param content 写入文件的内容
     */
    public void downloadFile(HttpServletRequest request, HttpServletResponse response, String fileName, String content) {
        try {
            response.setContentType("application/octet-stream; charset=utf-8");
            InputStream inputStream = new ByteArrayInputStream(content.getBytes());
            String userAgent = request.getHeader("User-Agent");
            if (userAgent.contains(BrowserType.BROWSER_MSIE) || userAgent.contains(BrowserType.BROWSER_TRIDENT)) {
                // 针对IE或者以IE为内核的浏览器：
                fileName = java.net.URLEncoder.encode(fileName, "UTF-8");
            } else {
                // 非IE浏览器的处理：
                fileName = new String(fileName.getBytes("UTF-8"), "ISO-8859-1");
            }
            // 设置响应 设置编码 设置响应头信息 文件下载
            response.setContentType("application/force-download");
            response.setCharacterEncoding("UTF-8");
            response.setHeader("Content-Disposition", "attachment;fileName=" + fileName);
            IOUtils.copy(inputStream, response.getOutputStream());
            response.flushBuffer();
        } catch (Exception e) {
            log.info("文件下载失败====>{}", e);
        }
        return;
    }
}
